package com.zhao.framework;

import java.util.Hashtable;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * 
 * 使用easyweb框架的通用servlet，它以singleton形式实现了IApiFactory接口。
 * 如果不对factory有特殊要求，建议servlet直接继承本类。
 * 这样继承者只要在setup中调用registerImplement注册各classfullpathname跟implement之间的对应关系。
 */
public abstract class GenericServlet extends AbstractServlet implements IApiFactory {
	protected static final Log log = LogFactory.getLog(GenericServlet.class); 
	static private Map<String,Class> implClz = new Hashtable<String,Class>();
	static private Map<String,Object> instances = new Hashtable<String,Object>();
	
	/**
	 * 继承者要在setup中调用本方法注册类名和实现类的映射关系。
	 * @param clzName 类名或接口名 
	 * @param impl 用来实例化的实现类
	 */
	protected void registerImplement(String clzName,Class impl) {
		addFactory(clzName,this);
		implClz.put(clzName,impl);
	}


	public Object getApiInstance(String classFullPathName) {
		Class clz = implClz.get(classFullPathName);
		if(null == clz){
			return null;
		}
		Object instance = instances.get(classFullPathName);
		if(null != instance){
			if(instance instanceof SessionHolder){
				
				try {
					instance = clz.newInstance();
				} catch (Exception e) {
					log.error("fail to create instance for class:<"+clz.getName()+">",e);
					return null;
				}
			}
			return instance;
		}

		synchronized(GenericServlet.class){
			instance = instances.get(classFullPathName);
			if(null != instance){
				return instance;
			}
			try {
				instance = clz.newInstance();
			} catch (Exception e) {
				log.error("fail to create instance for class:<"+clz.getName()+">",e);
				return null;
			}
			instances.put(classFullPathName, instance);
			return instance;
		}
	}


	@Override
	abstract protected void setup();

}
